using System;
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using System.Text;
using ECommerce.DAL;

namespace Entity
{
	/// <summary>
	/// This object represents the Private Fields of TblVideo.
	/// </summary>
	
	[System.ComponentModel.DataObject]
    public partial class TblVideo : DatabaseUtility
    {
		#region TblVideo Private Fields


		Int32 _videoID;
		String _title = String.Empty;
		String _description = String.Empty;
		String _videoPath = String.Empty;
		String _thumbPath = String.Empty;
		DateTime _dateUploaded;
		Boolean? _isDeleted;
		
		#endregion
		#region TblVideo Constractor
		/// <summary>
        /// Creates an empty object of TblVideo. 
        /// This is mainly used to create a new instance of TblVideo to add a new TblVideo.
        /// </summary>
		public TblVideo(){}
		
				
		/// <summary>
        /// Used to retrieve employee information from database, 
        /// which is also used by Update method to save information of an existing TblVideo.
        /// </summary>
		public TblVideo
		(
			
			Int32 videoID,
			
			String title,
			
			String  description,
			
			String videoPath,
			
			String thumbPath,
			
			DateTime dateUploaded,
			
			Boolean? isDeleted
		)
		{
			_videoID = videoID;	
			_title = title;	
			_description = description;	
			_videoPath = videoPath;	
			_thumbPath = thumbPath;	
			_dateUploaded = dateUploaded;	
			_isDeleted = isDeleted;	
		}
		
		#endregion
		#region TblVideo Properties
		
		 /***********************************************************************************************
                                    -- PROPERTIES --        
         Contains all the properties representing the data fields of the current entity.
         ***********************************************************************************************/

        /// <summary>
        /// This is the Primary key value of the VideoID, which can't be assigned from the application,
        /// to ensure the data consistancy, by not letting the user to change the PK_Video to update the data of an another TblVideo instance.
        /// For view or updation purpose, every TblVideo will be retrieved thru the proper 'Get' method.
        /// </summary>
		
		public Int32  VideoID
		{
			get {return _videoID;}	
		}
		
				
		public String  Title
		{
			get {return _title;}
			set {_title = value;}
		}

		public String  Description
		{
			get {return _description;}
			set {_description = value;}
		}

		public String  VideoPath
		{
			get {return _videoPath;}
			set {_videoPath = value;}
		}

		public String  ThumbPath
		{
			get {return _thumbPath;}
			set {_thumbPath = value;}
		}

		public DateTime  DateUploaded
		{
			get {return _dateUploaded;}
			set {_dateUploaded = value;}
		}

		public Boolean?  IsDeleted
		{
			get {return _isDeleted;}
			set {_isDeleted = value;}
		}
		

		#endregion
		#region TblVideo Static Methods
		/************************************************************************************
                                    -- CREATE METHOD (STATIC) --
        *************************************************************************************/
		/************************* Architecure note:**********************************
        Note 1:
        This method is specially useful for the case, where we need to use Object Data Source controls.
        For ObjectDataSource/SqlDataSource controls, the insert/update metnod requires paramters methods, rather property based methods.
        However, there is still a way to pass property based objects as method parameter for data source controls, 
        but in that case we could not use Sql type, as view controls or asp parameter control can only contain few of primitive type.
        The main reason to remain the Sql Type in our object architecture is it is faster and contains better way for null value support.
        
        Note 2: 
        Non-primary key: it should be primitive type, as the asp paramter control (included in data source control) supports only primitive types.
        /*****************************************************************************/
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Insert, true)]
        public static  Int32 CreateNewTblVideo
		(
			String title,
			String description,
			String videoPath,
			String thumbPath,
			DateTime dateUploaded,
			Boolean isDeleted
		)
		{
			//creating an empty TblVideo object
            TblVideo tblVideo = new TblVideo();
				tblVideo.Title = title;
				tblVideo.Description = description;
				tblVideo.VideoPath = videoPath;
				tblVideo.ThumbPath = thumbPath;
				tblVideo.DateUploaded = dateUploaded;
				tblVideo.IsDeleted = isDeleted;
			
			return TblVideo.CreateNewTblVideo(tblVideo);
		}
	
		/************************************************************************************
                 -- UPDATE METHODS (STATIC) --
        *************************************************************************************/

        /************************* Architecure note:**********************************
        Note 1:
        This method is specially useful for the case, where we need to use Object Data Source controls.
        For ObjectDataSource/SqlDataSource controls, the insert/update metnod requires paramters methods, rather property based methods.
        However, there is still a way to pass property based objects as method parameter for data source controls, 
        but in that case we could not use Sql type, as view controls or asp parameter control can only contain few of primitive type.
        The main reason to remain the Sql Type in our object architecture is it is faster and contains better way for null value support.
        
        Note 2: 
        There the two types of paramaters will be passed here.
         * a. Primary key paramater: it should be Sql type, as we will bind the primary key property for the view controls (form view, details view etc) as datakey.
         * b. Non-primary key: it should be primitive type, as the asp paramter control (included in data source control) supports only primitive types.
        /*****************************************************************************/
		
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static  bool UpdateTblVideo
		(
			Int32 videoID,
			String title,
			String description,
			String videoPath,
			String thumbPath,
			DateTime dateUploaded,
			Boolean isDeleted
		)
		{
			 TblVideo tblVideo =  TblVideo.GetTblVideoByVideoID(videoID);
			
				tblVideo.Title = title;
				tblVideo.Description = description;
				tblVideo.VideoPath = videoPath;
				tblVideo.ThumbPath = thumbPath;
				tblVideo.DateUploaded = dateUploaded;
				tblVideo.IsDeleted = isDeleted;
			
			return TblVideo.UpdateTblVideo(tblVideo);
		}

		/************************************************************************************
                         -- DELETE METHODS --
        *************************************************************************************/
        /************************* Architecure note:**********************************
        We have used the employeeId parameter as SqlInt32, to bind the delete method with object data source and view control directly.
        ****************************************************************************/
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, true)]
        public static  bool DeleteTblVideo
		(
			Int32 videoID
		)
		{
			//Validate Input
			if(videoID <= GetVideoIDMinValue)
				throw (new ArgumentOutOfRangeException("videoID"));
				
			// Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
			AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
			               AddParameterToSqlCmd(sqlCmd, "@VideoID",SqlDbType.Int, 0, ParameterDirection.Input, videoID);
			SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLVIDEO_DELETETBLVIDEO);
			ExecuteScalarCmd(sqlCmd);
			int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
			return (returnValue == 0 ? false : true);
			
		}
		
		/// <summary>
        /// Deletes a set of employees from the database.
        /// </summary>
		public static bool DeleteTblVideoList( System.Collections.Generic.List<Int32 >  videoIDListToDelete)
		{
			//Validate Input
			foreach (Int32 videoID in videoIDListToDelete)
			    if(videoID <= GetVideoIDMinValue)
					throw (new ArgumentOutOfRangeException("videoID"));
			
			//performing deletion operation //

            string xmlString = FormatXMLForIdArray(videoIDListToDelete);
			
			// Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
			AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            AddParameterToSqlCmd(sqlCmd, "@VideoIDList", SqlDbType.Xml, xmlString.ToString().Length, ParameterDirection.Input, xmlString.ToString());
			SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLVIDEO_DELETETBLVIDEOLIST);
			ExecuteScalarCmd(sqlCmd);
			int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
			return (returnValue == videoIDListToDelete.Count ? true : false);
		}
		
		/************************************************************************************
                                 -- GET BY PRIMARY METHODS --
        *************************************************************************************/
        /************************* Architecure note:**********************************
        Retrives an Employee from database, based on it's primary key.
        To view or update an employee, everytime we must have to use this type of 'get' method, 
        since we don't have direct access to the Primary key value for assigning value.
        We have used the employeeId parameter as SqlInt32, to bind the delete method with object data source and view control directly.
        /*****************************************************************************/
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
		public static TblVideo GetTblVideoByVideoID(Int32 videoID)
		{
			if(videoID <= GetVideoIDMinValue)
					throw (new ArgumentOutOfRangeException("videoID"));
				
		 	// Execute SQL Command
			SqlCommand sqlCmd = new SqlCommand();
			               AddParameterToSqlCmd(sqlCmd, "@VideoID",SqlDbType.Int, 0, ParameterDirection.Input, videoID);
			SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLVIDEO_GETTBLVIDEOBYVIDEOID);
			GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblVideoCollectionFromReader);
            CustomCollection<TblVideo> objCollection = ((CustomCollection<TblVideo>)ExecuteReaderCmd(sqlCmd, test));

            if (objCollection.Count > 0)
                return objCollection[0];
            else
                return null;
		}
		
		/************************************************************************************
                         -- GET BY FOREIGN KEY METHODS --
        *************************************************************************************/
		
		/************************************************************************************
                 -- GET ALL METHODS --
        *************************************************************************************/
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static CustomCollection<TblVideo> GetAllTblVideo()
		{
		
		 	// Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLVIDEO_GETALLTBLVIDEO);
            GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblVideoCollectionFromReader);
            CustomCollection<TblVideo> objCollection = ((CustomCollection<TblVideo>)ExecuteReaderCmd(sqlCmd, test));

            return objCollection;
		}
		
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static CustomCollection<TblVideo> GetAllTblVideoPaged(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            //Validate Input
            if (orderBy == "")
                orderBy = "VideoID";

            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();
            AddParameterToSqlCmd(sqlCmd, "@orderby", SqlDbType.VarChar, 50, ParameterDirection.Input, orderBy);
            AddParameterToSqlCmd(sqlCmd, "@startrow", SqlDbType.Int, 0, ParameterDirection.Input, startRowIndex);
            AddParameterToSqlCmd(sqlCmd, "@pagesize", SqlDbType.Int, 0, ParameterDirection.Input, maximumRows);

            SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLVIDEO_GETALLTBLVIDEOPAGED);

            GenerateCollectionFromReader test = new GenerateCollectionFromReader(GenerateTblVideoCollectionFromReader);
            CustomCollection<TblVideo> objCollection = ((CustomCollection<TblVideo>)ExecuteReaderCmd(sqlCmd, test));
            return objCollection;
        }
		
		[System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Select, true)]
        public static int GetAllTblVideoPagedCount(String orderBy, Int32 startRowIndex, Int32 maximumRows)
        {
            // Execute SQL Command
            SqlCommand sqlCmd = new SqlCommand();

            AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLVIDEO_GETALLTBLVIDEOPAGEDCOUNT);
            ExecuteScalarCmd(sqlCmd);

            int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
            return returnValue;
        }
		
		#endregion
		#region Employee Instance Methods
		/************************************************************************************
                                    -- SAVE (INSERT/UPDATE) METHODS (INSTANCE) --
        *************************************************************************************/
		/// <summary>
        /// Saves (inserts and updates) an Employee into database.
        /// The insertion occur if the EmployeeId conatins default value.
        /// Otherwises it updates the Employee into the database, based on the primary key value stored in EmployeeId.
        /// This technique ensures an Employee will not be updated without having a valid EmployeeId.
        /// </summary>
		public bool Save()
		{
			if(VideoID<= GetVideoIDMinValue)
			{
				Int32  TempId=CreateNewTblVideo(this);
				if(TempId>0)
				{
					_videoID=TempId;
					return true;
				}
				else
				{
					// error occurs
					return false;
				}
			}
			else
			{	//This is a update Command
				return (UpdateTblVideo(this));
			}
			
		}
		
		public static Int32  CreateNewTblVideo(TblVideo newTblVideo)
		{
			// validate Parameters
			if (newTblVideo == null)
				throw (new ArgumentNullException("newTblVideo"));

			// Execute SQL Command
			SqlCommand sqlCmd = new SqlCommand();
			int length = 0;
			AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            
			               AddParameterToSqlCmd(sqlCmd, "@Title",SqlDbType.NVarChar, 100, ParameterDirection.Input, newTblVideo.Title);
			if ( newTblVideo.Description!=null)
               AddParameterToSqlCmd(sqlCmd, "@Description",SqlDbType.Text, -1, ParameterDirection.Input, newTblVideo.Description);
            else
               AddParameterToSqlCmd(sqlCmd, "@Description",SqlDbType.Text, -1, ParameterDirection.Input ,System.DBNull.Value);
			               AddParameterToSqlCmd(sqlCmd, "@VideoPath",SqlDbType.NVarChar, 200, ParameterDirection.Input, newTblVideo.VideoPath);
			               AddParameterToSqlCmd(sqlCmd, "@ThumbPath",SqlDbType.NVarChar, 200, ParameterDirection.Input, newTblVideo.ThumbPath);
			               AddParameterToSqlCmd(sqlCmd, "@DateUploaded",SqlDbType.DateTime, 0, ParameterDirection.Input, newTblVideo.DateUploaded);
			if ( newTblVideo.IsDeleted!=null)
               AddParameterToSqlCmd(sqlCmd, "@IsDeleted",SqlDbType.Bit, 0, ParameterDirection.Input, newTblVideo.IsDeleted);
            else
               AddParameterToSqlCmd(sqlCmd, "@IsDeleted",SqlDbType.Bit, 0, ParameterDirection.Input ,System.DBNull.Value);
			
			SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLVIDEO_CREATENEWTBLVIDEO);
			ExecuteScalarCmd(sqlCmd);
			return (Int32.Parse(sqlCmd.Parameters["@ReturnValue"].Value.ToString()));

		}
		/// <summary>
        /// Updates an TblVideo instance to the database.
        /// </summary>
		public static bool UpdateTblVideo(TblVideo newTblVideo)
		{
			// validate Parameters
			if (newTblVideo == null)
				throw (new ArgumentNullException("newTblVideo"));

			// Execute SQL Command
			SqlCommand sqlCmd = new SqlCommand();
			int length = 0;
			AddParameterToSqlCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            
			               AddParameterToSqlCmd(sqlCmd, "@VideoID",SqlDbType.Int, 0, ParameterDirection.Input, newTblVideo.VideoID);
			               AddParameterToSqlCmd(sqlCmd, "@Title",SqlDbType.NVarChar, 100, ParameterDirection.Input, newTblVideo.Title);
			if ( newTblVideo.Description!=null)
               AddParameterToSqlCmd(sqlCmd, "@Description",SqlDbType.Text, -1, ParameterDirection.Input, newTblVideo.Description);
            else
               AddParameterToSqlCmd(sqlCmd, "@Description",SqlDbType.Text, -1, ParameterDirection.Input ,System.DBNull.Value);
			               AddParameterToSqlCmd(sqlCmd, "@VideoPath",SqlDbType.NVarChar, 200, ParameterDirection.Input, newTblVideo.VideoPath);
			               AddParameterToSqlCmd(sqlCmd, "@ThumbPath",SqlDbType.NVarChar, 200, ParameterDirection.Input, newTblVideo.ThumbPath);
			               AddParameterToSqlCmd(sqlCmd, "@DateUploaded",SqlDbType.DateTime, 0, ParameterDirection.Input, newTblVideo.DateUploaded);
			if ( newTblVideo.IsDeleted!=null)
               AddParameterToSqlCmd(sqlCmd, "@IsDeleted",SqlDbType.Bit, 0, ParameterDirection.Input, newTblVideo.IsDeleted);
            else
               AddParameterToSqlCmd(sqlCmd, "@IsDeleted",SqlDbType.Bit, 0, ParameterDirection.Input ,System.DBNull.Value);
			
			SetCommandType(sqlCmd,CommandType.StoredProcedure,SPR_TBLVIDEO_UPDATETBLVIDEO);
            ExecuteScalarCmd(sqlCmd);
			int returnValue = (int)sqlCmd.Parameters["@ReturnValue"].Value;
			return (returnValue == 0 ? false : true);
		}
		#endregion
		
		#region TblVideo Related Collections
		/// <summary>
        /// Creates and returns a strongly typed collection of Employee custom entity. 
        /// The colelction is created through iterating on the IdataReader object which contains Employee information, as a set of records, similar to tabular format.
        /// </summary>
		public static CollectionBase  GenerateTblVideoCollectionFromReader(IDataReader returnData) 
		{
			
			//creating the instance of Employee collection
			CustomCollection<TblVideo> colTblVideo = new CustomCollection<TblVideo>();
			
			Boolean? null_Boolean=null;
			Int32? null_Int32=null;
			Int16? null_Int16=null;
			Decimal? null_Decimal=null;
			DateTime? null_DateTime=null;
			Int64? null_Int64=null;
			Double? null_Double=null;
			/************************* Architecure note:**********************************
             * Below code includes the null value functionality to retieve the data which has nill value in database end.
             * Design consideration:
             * Besides general data fields, special care should be taken for primary keys, to assign '0'/defaultvalue, rather passing 'Null' value in constructor parameter.
             * Although we are considering sqldb tyoe data for the current data container, but while retireving data from database end, through datareader object, we need to cast data reader objects using .net primitive data type, 
             * rather using sqldb type to cast, since data reader objects don't support sql db type to be casted.
             *****************************************************************************/

            //Iterating thriugh the data reader, to generate Employee collection.

			//getting the Employee collection by iterating thru the data reader
			while (returnData.Read()) 
			{
				//passing the TblVideo constructor parameters from the current instance of data reader fields.
				TblVideo newTblVideo = new TblVideo
				(
					returnData["VideoID"]== System.DBNull.Value ? GetVideoIDMinValue : (Int32) returnData["VideoID"],
					returnData["Title"]== System.DBNull.Value ? string.Empty: (String ) returnData["Title"],
					returnData["Description"]== System.DBNull.Value ? null: (String ) returnData["Description"],
					returnData["VideoPath"]== System.DBNull.Value ? string.Empty: (String ) returnData["VideoPath"],
					returnData["ThumbPath"]== System.DBNull.Value ? string.Empty: (String ) returnData["ThumbPath"],
					returnData["DateUploaded"]== System.DBNull.Value ? DateTime.MinValue: (DateTime ) returnData["DateUploaded"],
					returnData["IsDeleted"]== System.DBNull.Value ? null_Boolean: (Boolean ) returnData["IsDeleted"]

				);
				//adding the Employee to the collection
				colTblVideo.Add(newTblVideo);
			}
			
			//returns the collection of Companys 
			return (colTblVideo);
		}
		
		#endregion
		#region Constants and Default Values
		
		public static Int32  GetVideoIDMinValue
		{
			get
			{
				return 0;
			}
		}
		
		//create method related contants
			internal const string SPR_TBLVIDEO_CREATENEWTBLVIDEO="spr_TblVideo_CreateNewTblVideo";
			internal const string SPR_TBLVIDEO_UPDATETBLVIDEO="spr_TblVideo_UpdateTblVideo";
			internal const string SPR_TBLVIDEO_DELETETBLVIDEO="spr_TblVideo_DeleteTblVideo";
			internal const string SPR_TBLVIDEO_DELETETBLVIDEOLIST="spr_TblVideo_DeleteTblVideoList";
			internal const string SPR_TBLVIDEO_GETTBLVIDEOBYVIDEOID="spr_TblVideo_GetTblVideoByVideoID";
			internal const string SPR_TBLVIDEO_GETALLTBLVIDEO="spr_TblVideo_GetAllTblVideo";
			internal const string SPR_TBLVIDEO_GETALLTBLVIDEOPAGED="spr_TblVideo_GetAllTblVideoPaged";
			internal const string SPR_TBLVIDEO_GETALLTBLVIDEOPAGEDCOUNT="spr_TblVideo_GetAllTblVideoPagedCount";
		
		#endregion
	}
}	
